package cc.verywell.pureblock.timelog;

import cc.verywell.pureblock.msg.p2p.P2pTimelog;
import cc.verywell.pureblock.net.AioProvider;
import cc.verywell.pureblock.net.NormalSession;
import cc.verywell.pureblock.net.Timelog;

/**
* 
* Copyright © 2019 TanYaqiu. All rights reserved.
* @author TanYaqiu 
* @address flat 601
* @date 2019年3月20日 上午1:51:40
*/
public class RecordLastOnlyTimelog implements Timelog,P2pTimelog {
	
	static public void useMe() {
		AioProvider.timelog = new TimelogGenerator() {
			@Override
			public Timelog getTimelog(NormalSession nss) {
				 return new RecordLastOnlyTimelog();
			}
		};
	}

	final public long connectbegin = System.currentTimeMillis();
	public long lastReadTime = connectbegin; //必要,timeout要用
	public long lastWriteTime = connectbegin; //必要,timeout要用
	public long read = 0; //非必要
	public long worte = 0; //非必要
	@Override
	public void read(int size) {
		lastReadTime = System.currentTimeMillis();
		read += size;
	}
	@Override
	public void worte(int size) {
		lastWriteTime = System.currentTimeMillis();
		worte += size;
	}
	@Override
	public long getLastWriteTime() {
		return lastWriteTime;
	}
	@Override
	public long getLastReadTime() {
		return lastReadTime;
	}
	public long getHandshakedTime() {
		return connectbegin;
	}
	public long totalRead() {
		return read;
	}
	public long totalWorte() {
		return worte;
	}
	
	/////////////////////////////////////////////////////////////////////////
	private long remoteSentTime;
	private long localReceiveTime;
	private long remoteTimeOffset = 0;
	private long remoteTimeTolerance = -1;
	private long pingUsedTimeMax = -1;
	@Override
	public void initTime(long remoteSentTime, long localReceiveTime) {
		this.remoteSentTime = remoteSentTime;
		this.localReceiveTime = localReceiveTime;
		this.remoteTimeOffset = remoteSentTime-localReceiveTime;
	}
	@Override
	public long getRemoteTimeOffset() {
		return remoteTimeOffset;
	}
	@Override
	public void receivedTimePing(long lastTimePeriod, long remoteTimeSent, long localTimeReceive) {
		this.remoteSentTime = remoteTimeSent;
		this.localReceiveTime = localTimeReceive;
		this.remoteTimeTolerance = (localTimeReceive-remoteTimeSent+lastTimePeriod)/2;
		this.remoteTimeOffset = this.remoteSentTime+this.remoteTimeTolerance-this.localReceiveTime;
	}
	@Override
	public void receivedTimePong(long lastTimePeriod, long localTimeSent, long remoteTimeSent, long localTimeReceive) {
		receivedTimePing(lastTimePeriod, remoteTimeSent, localTimeReceive);
		long timeUsed = localTimeReceive-localTimeSent;
		if(timeUsed>this.pingUsedTimeMax)this.pingUsedTimeMax=timeUsed;
	}
	@Override
	public long getLastTimePeriod() {
		return localReceiveTime-remoteSentTime;
	}
	@Override
	public long getRemoteTimeTolerance() {
		return remoteTimeTolerance;
	}
	@Override
	public long getP2PtimeOut() {
		return pingUsedTimeMax;
	}

	
	
}
